/**
 * <p>Title: FlowRuleNacosPublisher</p>
 *
 * <p>Description:</p>
 *
 * <p>Copyright: Copyright (c) 2022</p>
 *
 * <p>Company: www.sxdachang.com/</p>
 *
 * @author zhanyang
 * @date 2022/4/28
 * @version 1.0
 */

package com.alibaba.csp.sentinel.dashboard.nacos.flow;

import java.util.List;

import com.alibaba.csp.sentinel.dashboard.nacos.NacosConstants;
import com.alibaba.csp.sentinel.dashboard.nacos.NacosPropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.nacos.api.config.ConfigService;

/**
 * 将通过Sentinel Dashboard上维护的流控规则数据持久化到Nacos中
 * @author gang.wang
 * 2021年11月8日
 */
@Service
public class FlowRuleNacosPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {

    private static Logger logger = LoggerFactory.getLogger(FlowRuleNacosPublisher.class);

    @Autowired
    private NacosPropertiesConfiguration nacosConfigProperties;

    @Autowired
    private ConfigService configService;

    @Autowired
    private Converter<List<FlowRuleEntity>, String> converter;

    @Override
    public void publish(String appName, List<FlowRuleEntity> rules) throws Exception {

        if(StringUtils.isBlank(appName)) {
            logger.error("传入的AppName为Null");
            return ;
        }

        if(null == rules) {
            logger.error("传入的流控规则数据为null");
            return ;
        }

        String dataId = new StringBuilder(appName).append(NacosConstants.FLOW_DATA_ID_POSTFIX).toString();

        configService.publishConfig(dataId, nacosConfigProperties.getGroupId(), converter.convert(rules));

    }
}